import React, { useEffect, useState } from 'react';
import cn from 'classnames';
import s from './style.module.css';
import i from '@/index.module.css';
import { modifySysUpdate,getSystemDisk } from '~/API/index';
import { getErrorMessage } from '@/common/constant';
import { Radio, Upload, Button, Dialog, Loading, Link, Progress, Message } from '@knownsec/react-component';
export default function SystemUpdate() {
  const text=JSON.parse(localStorage.oem)
  const [updateLoading, setUpdateLoading] = React.useState(false);
  const [upVisible, setUpVisible] = useState(false);
  const [percent, setPercent] = useState(0);
  const [isFull, setIsFull] = useState('');
  const [updateData, setUpdateData] = React.useState({
    current: '--',
    cycle_value: 0,
    device_id: '',
    manual_system: false,
    next: '',
    server: '',
    status: 3,
    license_status: '有效',
    updated_at: '--',
    upgrade_type:'system'
  });
  useEffect(() => {
    getSysUpdate();
  }, []);
  useEffect(() => {
    ddisk();
  }, [updateData]);
  const changeVisible = () => {
    setUpVisible(false);
    setPercent(0);
  };
  const getSysUpdate = () => {
    setUpdateLoading(true);
    modifySysUpdate('GET', { tag: 'system' })
      .then((res) => {
        if (res.status === 'success') {
          setUpdateLoading(false);
          setUpdateData(res.data);
        }
      })
      .catch((err) => {
        Message.show({
          type: 'error',
          message: getErrorMessage(err, 'data'),
        });
      });
  };
  const changeManual = (val) => {
    modifySysUpdate('PUT', {
      tag: 'system',
      manual: val ? 1 : 0,
    })
      .then((res) => {
        if (res.status === 'success') {
          Message.show({
            type: res.status,
            message: res.message,
          });
          getSysUpdate();
        }
      })
      .catch((err) => Message.show({ type: 'error', message: getErrorMessage(err, 'data') }));
  };
  const uploadManual = ({ file }) => {
    setPercent(0);
    setUpVisible(true);
    let timer = null;
    let per = 0;
    timer = setInterval(() => {
      if (per > 87) {
        clearInterval(timer);
      } else {
        const d = Math.ceil(Math.random() * 10);
        per += d;
        setPercent((x) => (x += d));
      }
    }, 300);
    const formData = new FormData();
    formData.append('upgrade_type', 'system');
    formData.append('update_file', file);
    modifySysUpdate('POST', formData, true)
      .then((res) => {
        clearInterval(timer);
        setPercent(100);
        setUpVisible(false);
        Message.show({
          type: res.status,
          message: res.message,
          onclose: () => {
            if (res.status === 'success') {
              getSysUpdate();
              setPercent(0);
            }
          },
        });
      })
      .catch((err) => {
        setUpVisible(false);
        setPercent(0);
        Message.show({
          type: 'error',
          message: getErrorMessage(err, 'data'),
        });
      });
  };
  const ddisk = async () => {
    const res = await getSystemDisk({ master: 1 });
    let text=''
    if (res.data?.threshold<=res.data?.out_memery?.sys_usage) {
        text='当前磁盘所需空间不足，无法更新最新版本'
    }
    if(updateData.license_status !== '有效'){
        text='产品证书已失效， 无法更新最新版本'
    }
    setIsFull(text);
  };
  return (
    <>
      <div className={s.bgc}>
        <div className={cn(i.pr)}>
          <Loading show={updateLoading} label="" />
          <div className={cn(i.pt24, i.pl20, i.pr20, i.pb20)}>
            <p className={s.wordMain_h} style={{ display: isFull ? 'block' : 'none' }}>
              {isFull}
            </p>
            <div>
              <span className={s.bound}>系统版本：</span>
              <span className={i.ml24}>
                {updateData.system_version}&nbsp;
              </span>
            </div>
            <div className={cn(i.mt20)}>
              <span className={s.bound}>最近更新时间：</span>
              <span className={i.ml24}>{updateData.updated_at || '--'}</span>
            </div>
            <div className={cn(i.df, i.aifs, i.mt20)}>
              <div className={s.bound}>升级方式：</div>
              <div className={cn(i.ml24, s.mt_4, i.blackLineColor)}>
                <Radio.Group
                  value={updateData.manual_system}
                  onChange={(e) => {
                    changeManual(e.target.value);
                  }}
                >
                  <Radio value={false} className={cn(i.db, i.blackLineColor)}>
                      自动升级，每{updateData.cycle_value}
                      个小时访问此升级服务器（如您的服务器不能访问外网，请手动选择升级）
                  </Radio>
                  <Radio value={true} className={i.mt15}>
                    <span className={i.blackLineColor}>手动升级</span>
                    <Upload
                      className={cn(i.dib, i.ml15)}
                      customRequest={uploadManual}
                      showUploadList={false}
                      disabled={!updateData.manual_system}
                    >
                      <Button type="primary" disabled={!updateData.manual_system}>
                          上传文件并升级
                      </Button>
                    </Upload>
                  </Radio>
                </Radio.Group>
              </div>
            </div>
          </div>
          {text.home==='北京知道创宇信息技术股份有限公司'&&<div className={cn(i.df, i.aifs, s.mt40, s.infos)}>
            <div className={cn(i.pr, s.t2)}>
              <svg
                width="95px"
                height="18px"
                viewBox="0 0 82 18"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                xlink="http://www.w3.org/1999/xlink"
              >
                <g id="页面-1" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
                  <g id="系统管理-数据升级" transform="translate(-252.000000, -430.000000)">
                    <g id="编组" transform="translate(252.000000, 429.000000)">
                      <text
                        id="注意事项"
                        fontFamily="PingFangSC-Regular, PingFang SC"
                        fontSize="14"
                        fontWeight="normal"
                        fill="#333"
                      >
                        <tspan x="26" y="15">
                            注意事项：
                        </tspan>
                      </text>
                      <g id="警告" transform="translate(0.000000, 1.000000)">
                        <path
                          d="M11.0733391,1.28205881 L17.7547377,14.644856 C18.3273446,15.7900698 17.863155,17.1826386 16.7179412,17.7552455 C16.396026,17.9162031 16.0410568,18 15.6811447,18 L2.31834747,18 C1.03795952,18 0,16.9620405 0,15.6816525 C0,15.3217405 0.083796882,14.9667712 0.244754454,14.644856 L6.92615306,1.28205881 C7.49875996,0.136845012 8.89132878,-0.327344596 10.0365426,0.245262304 C10.4852063,0.469594185 10.8490072,0.833395047 11.0733391,1.28205881 Z"
                          id="三角形"
                          fill="#0B6FD6"
                        ></path>
                        <path
                          d="M9.00048189,14.2777778 C9.45125469,14.2777778 9.81667825,14.5513815 9.81667825,14.8888889 C9.81667825,15.2263962 9.45125469,15.5 9.00048189,15.5 C8.54970909,15.5 8.18428553,15.2263962 8.18428553,14.8888889 C8.18428553,14.5513815 8.54970909,14.2777778 9.00048189,14.2777778 Z M9.00048189,4.5 C9.82864287,4.5 10.5,4.97124896 10.5,5.55256402 L10.4986523,5.59718002 L9.56734454,13.2986796 C9.54214466,13.5067692 9.29416399,13.6666667 8.99664353,13.6666667 C8.69916901,13.6666667 8.45127148,13.5067291 8.4262485,13.2986614 L7.5054029,5.64177226 C7.43569878,5.06217811 8.04856209,4.55266044 8.87427142,4.50373269 C8.91624827,4.50124533 8.95835574,4.5 9.00048189,4.5 Z"
                          id="形状结合"
                          fill="#FFFFFF"
                        ></path>
                      </g>
                    </g>
                  </g>
                </g>
              </svg>
            </div>
            <div className={cn(s.ml32)}>
              <div className={i.blackLineColor}>手动升级需要上传升级文件，升级文件获取方式</div>
              <div className={cn(i.blackLineColor, i.mt20)}>
                  1.先访问
                <Link type="primary" href={updateData.server} target="_blank">
                  {updateData.server}
                </Link>
              </div>
              <div className={cn(i.blackLineColor, i.mt20)}>
                  2.输入<span className={i.mainColor}>license Key： {updateData.device_id}</span>
                  进行登录验证，成功登录后下载大于当前版本
                <span className={i.mainColor}>{updateData.system_version}</span>的所有升级文件
              </div>
              <div className={cn(i.blackLineColor, i.mt20)}>
                  3.在此页面点击“上传升级文件并升级”按钮，按照版本号从最小版本依次往上升级，直到升级到您最终想要的版本
              </div>
            </div>
          </div>}
        </div>
      </div>
      <Dialog
        className={cn(i.w400)}
        title="上传进度"
        visible={upVisible}
        cancelText=""
        confirmText=""
        onhide={() => {
          changeVisible();
          setPercent(0);
        }}
      >
        <div className={i.p20}>
          <p className={cn(i.tac)}>进度:{percent}%</p>
          <Progress percent={percent + '%'} className={i.mt10} />
        </div>
      </Dialog>
    </>
  );
}
